<?php

    #-------------------------------------------------------------#
	# This file is part of the Tekuna MVC Microframework for PHP. #
	# (c) 2009 Niels Jäckel <niels.jaeckel@tekuna.org>            #
	# Please visit http://tekuna.org/ for more information.       #
	#                                                             #
	# This software is licensed under the MIT License. Please     #
	# view the LICENSE file for the full text of this license.    #
    #-------------------------------------------------------------#


	// define the base path of all tekuna classes
	$sBaseDir = realpath('../../org/');

	// define root directory of the application
	define('APPLICATION_ROOT',  realpath('../../../'));

	// some classes must be included before
	include '../../bootstrap.php';

	// recover the handlers
	restore_error_handler();
	restore_exception_handler();

#print_r(get_included_files());

	// call the recursive inclusion function
	includeFilesRecursively($sBaseDir);


	function includeFilesRecursively($sDirectory) {

#echo "## including classes recursively for $sDirectory<br/>";

		$objDir = dir($sDirectory);

		while ($sFile = $objDir -> read()) {

			// skip invisible files and directories
			if ($sFile{0} == '.') {
#echo "~~~ skipping ($sFile)<br />";
				continue;
			}

			// get the full file path
			$sFullFile = $sDirectory . DIRECTORY_SEPARATOR . $sFile;

			// exclude test classes
			$sTestPathPattern = '~org.tekuna.test$~';
			if (preg_match($sTestPathPattern, $sFullFile, $arrRes)) {
#echo "~~~ IGNORING this directory ($sFullFile)<br />";
				continue;
			}

			// handle directories
			if (is_dir($sFullFile)) {

				// recurse into found directory
				includeFilesRecursively($sFullFile);
			}

			// handle files
			$sFilePattern = '~\.(class|abstract|interface)\.php$~';
			if (is_file($sFullFile) && preg_match($sFilePattern, $sFile, $arrRes)) {

				if (! in_array($sFullFile, get_included_files())) {
#echo "including $sFullFile<br />";
					include $sFullFile;
				}
				else {

#echo "~~~ file still loaded ($sFullFile)<br />";
				}
			}
			else {

#				if (is_file($sFullFile)) echo "~~~ file does not match ($sFile)<br />";
			}
		}
	}

